// model工具类

package common

import (
	"reflect"
	"strings"
)

//获取界面需要的JSON字符串
func GetModelDefJson(mode interface{}) map[string]interface{} {
	v := reflect.ValueOf(mode).Elem()
	t := v.Type()
	data := map[string]interface{}{}
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		input := field.Tag.Get("input")
		if input != "no" { //用户输入字段
			value, _ := GetFieldDefByTag(field)
			data[StrFirstToLower(t.Field(i).Name)] = value
		}
	}
	return data
}

//从Tag读取默认值
func GetFieldDefByTag(f reflect.StructField) (string, error) {
	orm := f.Tag.Get("orm")
	if orm == "" {
		return "", nil
	} else {
		var def = ""
		temp := strings.Split(orm, ";")
		for _, str := range temp {
			if strings.HasPrefix(str, "default(") {
				beginIndex := strings.Index(str, "default(")
				endIndex := strings.Index(str, ")")
				def = string([]byte(str)[beginIndex+8 : endIndex])
			}
		}
		return def, nil
	}
}

//获取MODEL的描述
func GetModelDesc(mode interface{}) map[string]interface{} {
	v := reflect.ValueOf(mode).Elem()
	t := v.Type()
	data := map[string]interface{}{}
	for i := 0; i < t.NumField(); i++ {
		tag := t.Field(i).Tag
		input := tag.Get("input")
		orm := tag.Get("orm")
		label := tag.Get("label")

		if input != "no" { //用户输入字段
			value := "字段名称：" + label + "，字段定义：" + orm + "，验证：" + tag.Get("valid")
			data[StrFirstToLower(t.Field(i).Name)] = value
		}
	}
	return data
}
